# -*- coding: utf-8 -*-
import os
import re
import json
import time
import requests
import socket
from datetime import datetime
import pywintypes
from win32com.client import Dispatch


#http://61.153.145.162:8888/getpositionTP.asp?regnum=浙B8E792
#http://61.153.145.162:8888/getpositionTP.asp?regnum=all
#电信地址
#http://221.12.55.171:8889/getpositionTP.asp?regnum=浙B8E792
#网通地址
#http://61.153.145.162:8888/getpositionTPM.asp?regnum=浙B8E792
# 跳转到51ditu
# http://61.153.145.162:8888/HQWEBGPS/WEBGIS/51dtA.htm?浙B8F661,2011年7月28日9:08:25,18,121.496198,30.121058
# 请求地址

# http://rgc.vip.51ditu.com/rgc?pos=12086389,3014611&type=1
# 反向地址解释地址，经度范围为7340000～13657591,纬度范围为323936～5523685

# <?xml version="1.0" encoding="GBK" ?><R> <code>0</code> <msg>浙江省绍兴市上虞市，纬三路和经九路交叉口西约120米处, 杭州湾精细化工园区公园西北约660米处</msg> </R>

# http://rgc.vip.51ditu.com/rgc?pos=12086389,3014611
# <?xml version="1.0" encoding="GBK" ?> <ReverseGeocode> <Geo lng="12086389"  lat="3014611"/> <Area regionCode="330682"> 浙江省-绍兴市-上虞市</Area> </ReverseGeocode>


        
def save_gps(jdata):
    oConn = Dispatch('ADODB.Connection')
    oConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\data\data.mdb;Jet OLEDB:Database Password=tp@chenkai"
    oConn.Open()
    oCmd = Dispatch('ADODB.Command')
    oCmd.ActiveConnection = oConn
    for x in jdata:
        print x
        cph=x['LicensePlate']
        print cph
        cl_lng=str(x['Geometry']['Coordinates'][0])
        cl_lat=str(x['Geometry']['Coordinates'][1])
        cl_timestamp=str(x['TimeStamp'])
        cl_speed=str(x['Speed'])
        cl_update=datetime.strftime(datetime.now(),"%Y/%m/%d %H:%M:%S")
        cl_reverse=getreverse(x['Geometry']['Coordinates'])
        oCmd.CommandText = "update cl set cl_lng="+cl_lng+",cl_lat="+cl_lat+",cl_timestamp="+cl_timestamp+",cl_speed="+cl_speed+",cl_update=\'"+cl_update+"\',cl_reverse=\'"+cl_reverse+"\' where cph=\'"+cph+"\'"
        print oCmd.CommandText
        
        oCmd.Execute()
    oCmd = None
    oConn.Close()
    oConn = None

def formatgeo(geo):
    s=str(round(geo,5))
    l=s.split(".")
    if len(l[1])>=5:
        l[1]=l[1][:5]
    else:
        l[1]=l[1]+"0"*(5-len(l[1]))
    # print l[1]
    s="".join(l)
    return s
        
def getreverse(lnglat):
    lng=formatgeo(lnglat[0])
    lat=formatgeo(lnglat[1])
    url="http://rgc.vip.51ditu.com/rgc?pos="+lng+","+lat+"&type=1"
    r = requests.get(url)
    print r.request.headers
    print r.encoding
    print r.url
    the_page = r.text
    print the_page
    pattern=r'<msg>.+?<\/msg>'
    reverse=re.search(pattern,the_page).group(0)
    pattern=r'<.+?>'
    reverse=re.sub(pattern,'',reverse)
    # reverse=unicode(reverse,"gbk")
    pattern=u'浙江省'
    reverse=re.sub(pattern,'',reverse)
    print reverse
    return reverse    


    
url="http://nbgps.shedi.com/webgis/getCarsByJson.php"

try:
    payload = {'username': 'xfwl', 'password': 'xf56', 'regnum': 'all'}
    r = requests.get(url, params=payload)
    jdata=r.json()
    print jdata
    save_gps(jdata)
except socket.error:
    pass
